package com.xian.hive;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * 统计表记录数
 */
public class GetTableSumRow {
    public static void main(String[] args) throws Exception {

        String projectDir = System.getProperty("user.dir");  //当前工作目录
        System.out.println("当前目录："+projectDir);



        Properties properties = new Properties();
        properties.load(new FileInputStream(projectDir+"/conf/db.properties"));

        String url = properties.getProperty("url");
        System.out.println("连接地址:"+ url);

        Class.forName("org.apache.hive.jdbc.HiveDriver");
        Connection con = DriverManager.getConnection(url);//密码为空  如果需要用户密码的，还需要改
        //System.out.println("hive con Info => " + con);
        Statement st = con.createStatement();


        //把所有结果汇总，写到文件中
        StringBuilder sb = new StringBuilder();

        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(projectDir + "/conf/count.sql")));
        String sql = null;
        while (null != (sql = reader.readLine())) {

            try {
                System.out.println("执行SQL:"+sql);
                ResultSet resultSet = st.executeQuery(sql); //判断try不存在不让它跳出
                while (resultSet.next()) {
                    String count = resultSet.getString(1);
                    sb.append(sql + "; -- 总记录数:" + count + "\n");
                }
                resultSet.close();
            } catch (SQLException e) {
                System.out.println("执行异常SQL:"+sql);
                e.printStackTrace();
            }

        }


        //关闭连接资源
        st.close();
        con.close();



        //写到文件中
        FileWriter writer = new FileWriter(projectDir + "/result.txt");
        writer.write(sb.toString());
        writer.close();


        System.out.println("程序执行完毕！");








    }
}
